package com.shiningstars.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.shiningstars.R;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.tools.DatePickerFragment;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.Feedback;

@SuppressLint("SimpleDateFormat")
public class TeacherFeedback1Activity extends FragmentActivity implements Constants, Messages, Config {

	Feedback feedback;

	Spinner spinnerCenterName;
	TextView textViewTeacherName;
	TextView textViewPathshalaDate;
	TextView textViewFeedbackDate;
	RadioGroup radioGroupBatchName;
	RadioButton aBatch;
	RadioButton bBatch;
	EditText editTextMainTopic;
	EditText editTextSutra;
	EditText editTextValue;
	EditText editTextStory;
	EditText editTextActivity;
	EditText editTextGame;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_teacher_feedback_1);

			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			SplashPageActivity.showSplash = false;

			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

			spinnerCenterName = (Spinner) findViewById(R.id.tf1Spinner1);
			textViewTeacherName = (TextView) findViewById(R.id.tf1TextView1);
			textViewPathshalaDate = (TextView) findViewById(R.id.tf1TextView2);
			textViewFeedbackDate = (TextView) findViewById(R.id.tf1TextView3);
			radioGroupBatchName = (RadioGroup) findViewById(R.id.tf1RadioGroup1);
			aBatch = (RadioButton) findViewById(R.id.tf1RadioButton1);
			bBatch = (RadioButton) findViewById(R.id.tf1RadioButton2);
			editTextMainTopic = (EditText) findViewById(R.id.tf1EditText1);
			editTextSutra = (EditText) findViewById(R.id.tf1EditText2);
			editTextValue = (EditText) findViewById(R.id.tf1EditText3);
			editTextStory = (EditText) findViewById(R.id.tf1EditText4);
			editTextActivity = (EditText) findViewById(R.id.tf1EditText5);
			editTextGame = (EditText) findViewById(R.id.tf1EditText6);

			String centerName = Utilities.getSharedPreference(getApplicationContext(), CENTER);
			spinnerCenterName.setSelection(Utilities.getCenterId(centerName), true);

			Calendar calendar = Calendar.getInstance();
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

			if (dayOfWeek < 7) {
				calendar.add(Calendar.DAY_OF_WEEK, -1 * dayOfWeek);
			}

			DateFormat df = new SimpleDateFormat(EEE);
			String day = df.format(calendar.getTime());

			if (SATURDAY.equals(day)) {
				String pathshalaDate = Utilities.getDate(calendar.get(Calendar.DATE), calendar.get(Calendar.MONTH),
						calendar.get(Calendar.YEAR));
				textViewPathshalaDate.setText(pathshalaDate);
			}

			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int date = c.get(Calendar.DATE);

			String name = Utilities.getSharedPreference(getApplicationContext(), NAME);
			String feedbackDate = Utilities.getDate(date, month, year);

			textViewTeacherName.setText(name);
			textViewFeedbackDate.setText(feedbackDate);

			if (null != getIntent()) {
				if (null != getIntent().getExtras()) {
					if (null != getIntent().getExtras().get(FEEDBACK)) {
						feedback = (Feedback) getIntent().getExtras().get(FEEDBACK);

						spinnerCenterName.setSelection(Utilities.getCenterId(feedback.getQuestion1()), true);
						textViewTeacherName.setText(feedback.getQuestion2());
						textViewPathshalaDate.setText(feedback.getQuestion3());
						textViewFeedbackDate.setText(feedback.getQuestion4());

						if (A_BATCH.equals(feedback.getQuestion5())) {
							aBatch.setChecked(true);
						} else if (B_BATCH.equals(feedback.getQuestion5())) {
							bBatch.setChecked(true);
						}

						editTextMainTopic.setText(feedback.getQuestion6());
						editTextSutra.setText(feedback.getQuestion7());
						editTextValue.setText(feedback.getQuestion8());
						editTextStory.setText(feedback.getQuestion9());
						editTextActivity.setText(feedback.getQuestion10());
						editTextGame.setText(feedback.getQuestion11());
					}
				}
			}

			if (null == feedback) {
				feedback = new Feedback();

				String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);
				String imeiNumber = Utilities.getSharedPreference(getApplicationContext(), IMEI_NUMBER);

				feedback.setMobileNumber(mobileNumber);
				feedback.setImeiNumber(imeiNumber);
				feedback.setDate(c.getTimeInMillis());
				feedback.setMode(APP);
				feedback.setIsSynced(N);
				feedback.setIsNotified(N);
				feedback.setIsRead(N);

				feedback.setQuestion2(name);
				feedback.setQuestion4(feedbackDate);
				feedback.setQuestion53(BLANK);
				feedback.setQuestion54(BLANK);
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback1Activity.class.getName(), e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.feedback_menu, menu);
			menu.removeItem(R.id.feedback_back);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback1Activity.class.getName(), e);
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			if (NEXT.equals(item.getTitle()) && validate()) {
				Intent i = new Intent(TeacherFeedback1Activity.this, TeacherFeedback2Activity.class);
				i.putExtra(FEEDBACK, feedback);
				startActivity(i);
				finish();
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback1Activity.class.getName(), e);
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(TeacherFeedback1Activity.this);

			builder.setMessage(FEEDBACK_CANCEL);
			builder.setCancelable(false);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Intent i = null;

					String currentRole = Utilities.getSharedPreference(getApplicationContext(), CURRENT_ROLE);
					if (ADMIN.equals(currentRole)) {
						i = new Intent(TeacherFeedback1Activity.this, AdminActivity.class);
					} else if (TEACHER.equals(currentRole)) {
						i = new Intent(TeacherFeedback1Activity.this, MyFeedbackActivity.class);
					}

					startActivity(i);
					finish();
				}
			});
			builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback1Activity.class.getName(), e);
		}
	}

	public void showDatePickerDialog(View v) {
		try {
			DialogFragment newFragment = new DatePickerFragment(com.shiningstars.R.id.tf1TextView2);
			newFragment.show(getSupportFragmentManager(), DATE_PICKER);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback1Activity.class.getName(), e);
		}
	}

	private boolean validate() {
		boolean isValid = true;
		String errorMessage = null;

		if (spinnerCenterName.getSelectedItemId() == 0) {
			isValid = false;
			errorMessage = INVALID_CENTER_NAME;
			spinnerCenterName.requestFocus();
		} else {
			feedback.setQuestion1(spinnerCenterName.getSelectedItem().toString());
		}

		String pathshalaDate = textViewPathshalaDate.getText().toString();
		if (isValid && NO_DATE_SELECTED.equals(pathshalaDate)) {
			isValid = false;
			errorMessage = INVALID_PATHSHALA_DATE;
			textViewPathshalaDate.requestFocus();
		} else {
			feedback.setQuestion3(pathshalaDate);
		}

		int radioButtonId = radioGroupBatchName.getCheckedRadioButtonId();
		if (isValid && radioButtonId == -1) {
			isValid = false;
			errorMessage = INVALID_BATCH;
			radioGroupBatchName.requestFocus();
		} else {
			if (radioButtonId == aBatch.getId()) {
				feedback.setQuestion5(aBatch.getText().toString());
			} else if (radioButtonId == bBatch.getId()) {
				feedback.setQuestion5(bBatch.getText().toString());
			}
		}

		String mainTopic = editTextMainTopic.getText().toString();
		if (isValid && Utilities.isBlankString(mainTopic)) {
			isValid = false;
			errorMessage = INVALID_MAIN_TOPIC;
			editTextMainTopic.requestFocus();
		} else {
			feedback.setQuestion6(mainTopic);
		}

		String sutra = editTextSutra.getText().toString();
		if (isValid && Utilities.isBlankString(sutra)) {
			isValid = false;
			errorMessage = INVALID_SUTRA;
			editTextSutra.requestFocus();
		} else {
			feedback.setQuestion7(sutra);
		}

		String value = editTextValue.getText().toString();
		if (isValid && Utilities.isBlankString(value)) {
			isValid = false;
			errorMessage = INVALID_VALUE;
			editTextValue.requestFocus();
		} else {
			feedback.setQuestion8(value);
		}

		String story = editTextStory.getText().toString();
		if (isValid && Utilities.isBlankString(story)) {
			isValid = false;
			errorMessage = INVALID_STORY;
			editTextStory.requestFocus();
		} else {
			feedback.setQuestion9(story);
		}

		String activity = editTextActivity.getText().toString();
		if (isValid && Utilities.isBlankString(activity)) {
			isValid = false;
			errorMessage = INVALID_ACTIVITY;
			editTextActivity.requestFocus();
		} else {
			feedback.setQuestion10(activity);
		}

		String game = editTextGame.getText().toString();
		if (isValid && Utilities.isBlankString(game)) {
			isValid = false;
			errorMessage = INVALID_GAME;
			editTextGame.requestFocus();
		} else {
			feedback.setQuestion11(game);
		}

		if (!isValid) {
			AlertDialog.Builder builder = new AlertDialog.Builder(TeacherFeedback1Activity.this);

			builder.setMessage(errorMessage);
			builder.setCancelable(false);
			builder.setTitle(ERROR);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		}

		return isValid;
	}

	@Override
	protected void onPause() {
		super.onPause();
		SplashPageActivity.showSplash = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (SplashPageActivity.showSplash) {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.activity_splash_page, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			findViewById(R.id.tf1Q1).post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(findViewById(R.id.tf1Q1), Gravity.CENTER, 0, 0);
				}
			});

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}
				}
			}, SPLASH_TIME_OUT);

			SplashPageActivity.showSplash = false;
		}
	}
}